const express = require('express');
const router = express.Router();
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const authenticator = require('../middleware/authenticator');

// 生成一个随机盐 
const salt = crypto.randomBytes(16).toString('hex');

const secretKey = 'pp7_secret_key';

const generateToken = (userId, username) => {
    const payload = {
        userId,
        username
    };
    const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });
    return token;
};

function userRouteModule(db) {

    // 注册接口
    router.post('/register', async (req, res) => {
        const { username, password, phone, email, gender } = req.body;
        // 创建哈希值
        const hash = crypto.createHmac('sha256', salt).update(password).digest('hex');
        const sql = 'INSERT INTO users (username, password, salt, phone, email, gender) VALUES (?,?,?,?,?,?)';

        try {
            const [rows] = await db.query('select * from users where username =?', [username]);
            if (rows.length > 0) {
                return res.status(401).send({ code: 401, message: '用户名已存在' });
            }

            const [result] = await db.query(sql, [username, hash, salt, phone, email, gender]);
            console.log(result, "result");
            res.status(200).send({ code: 200, msg: '注册成功' });

        } catch (error) {
            console.log(error, "错误");
            res.status(500).send({ code: 500, msg: '服务器错误' });
        }
    });

    // 登录接口
    router.post('/login', async (req, res) => {
        const { username, password } = req.body;
        try {
            console.log(username, password, "username, password");
            const [rows] = await db.query(
                'SELECT id, salt, password FROM users WHERE username =?',
                [username]
            );

            if (rows.length === 0) {
                return res.status(401).send({ message: '用户名或密码错误' });
            }

            const storedSalt = rows[0].salt;
            const storedHash = rows[0].password;
            const id = rows[0].id;

            // 使用相同的盐对输入的密码进行哈希处理
            const hash = crypto.createHmac('sha256', storedSalt).update(password).digest('hex');
            // 比较新生成的哈希值与数据库中存储的哈希值
            if (hash !== storedHash) {
                return res.status(401).send({ message: '用户名或密码错误' });
            }
            // 登录成功，生成 JWT
            const token = generateToken(id, username);

            // 返回 JWT
            res.header('Authorization', token).send({ code: 200, message: '登录成功', data: { token: token } });
        } catch (error) {
            console.log(error, "错误");
        }
    });

    // 得到用户信息
    // 得到用户信息和权限  authenticator, 
    router.get("/getInfo", async (req, res) => {
        const userId = req.userId; // 假设中间件authenticator解析了token并挂载到req.user上
        try {
            // 查询用户信息
            const [userRows] = await db.query(
                'SELECT id as userId, username, email, phone, gender FROM users WHERE id =?',
                [userId]
            );

            // 查询用户权限
            const [roleRows] = await db.query(
                'SELECT r.rolename FROM roles r JOIN user_roles ur ON r.id = ur.roleid WHERE ur.userid = ?',
                [userId]
            );

            if (userRows.length === 0) {
                return res.status(404).send({ code: 404, message: '用户未找到' });
            }

            const userInfo = userRows[0];
            const roleInfo = roleRows.length > 0 ? roleRows[0].rolename : '无权限';

            res.send({
                code: 200,
                data: {
                    ...userInfo,
                    role: roleInfo
                },
                message: "ok"
            });
        } catch (error) {
            console.log(error, "错误");
            res.status(500).send({ code: 500, message: '服务器错误' });
        }
    });

    return router;
}

module.exports = userRouteModule;